package com.example.flshtarvel.service;

import com.example.flshtarvel.entity.User;
import com.example.flshtarvel.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;


@Service
public class UserService {

    @Autowired(required = false)
    UserMapper userMapper;

    public User getUserById(String userId){
        System.out.println(userId);
        return userMapper.selectUserById(userId);
    }

    public User doLogin(User user){
        return userMapper.doLogin(user);
    }

    public List<User> getAllUser(int page,int size){
        //计算偏移量
        int offset = (page-1)*size;
        return userMapper.selectAllUser(offset,size);
    }

    public int selectUserCount(){
        return userMapper.selectUserCount();
    }

//    添加用户
    public int insertUser(User user){

        //检查是否已存在该用户名
        User userResult = userMapper.selectUserByName(user.getUserName());
        if(userResult==null){
            user.setUserId(UUID.randomUUID().toString());
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            user.setTime(df.format(new Date()));
            return userMapper.insertUser(user);
        }else{
            return 2;
        }


    }

//    注册用户
    public int register(User user){
        user.setUserId(UUID.randomUUID().toString());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setTime(df.format(new Date()));
        user.setRole(0);
        return userMapper.insertUser(user);
    }

    public int deleteUser(String userId){
        return userMapper.deleteUser(userId);
    }

    public int updateUser(User user){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setTime(df.format(new Date()));
        return userMapper.updateUser(user);
    }
}
